import config from "@/utils/env"; //引入接口共用地址
// import useUserStore from '@/store/user.js' //引入仓库，使用的是pinia

const { BASE_URL, APP_ID } = config;

export const request = (options) => {
  return new Promise((resolve, reject) => {
    // 获取用户令牌
    // let token = useUserStore().token
    // 设置请求头
    const header = {
      "Content-Type": "application/json",
      // Authorization: `Bearer ${token}`,
      ...options.header, // 可以传入额外的请求头参数
    };

    const params = options.data || {};
    params.token = uni.getStorageSync("token") || "";
    params.h5 = 1;
    params.app_id = APP_ID;
    console.log(`${BASE_URL}${options.url.replace(/^\/\s*/, "")}`);
    // ⭐在发送请求之前执行拦截操作
    uni.request({
      url: `${BASE_URL}${options.url}`, //接收请求的API
      method: options.method || "GET", //接收请求的方式,如果不传默认为GET
      data: params, //接收请求的data,不传默认为空
      header: header, //接收请求的header
      success(res) {
        if (res.statusCode !== 200) {
          return uni.$showMsg("请求失败");
        }

        // ⭐在这里处理接收到响应后处理响应数据
        if (res.data.code === -1 || res.data.code === -2) {
          // 提示重新登录
          uni.showToast({
            title: "请登录",
            icon: "none",
            mask: true,
          });
          // useUserStore().userLogout()
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/mine/Login",
            });
          }, 1000);
        }
        resolve(res.data); // 使用resolve将数据传递出去
      },
      fail: (err) => {
        reject(err);
      },
    });
  });
};

const _get = function (url, data = {}) {
  return request({
    url: url,
    method: "GET",
    data: data,
  });
};

const _post = function (url, data = {}) {
  return request({
    url: url,
    method: "POST",
    data: data,
  });
};

export default {
  _get,
  _post,
};
